package com.loong.system.handler;

import com.loong.common.utils.TransformUtils;
import com.loong.system.business.SystemPositionBusiness;
import com.loong.system.common.backend.param.SystemPositionParam;
import com.loong.system.common.backend.result.SystemPositionTreeResult;
import com.loong.system.model.SystemPosition;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Component
public class SystemPositionHandler {
    @Resource
    private SystemPositionBusiness systemPositionBusiness;

    /**
     * 保存位置信息
     * @param systemPositionParam
     */
    public void save(SystemPositionParam systemPositionParam){
        systemPositionBusiness.save(TransformUtils.transform(systemPositionParam, SystemPosition.class));
    }

    /**
     * 更新位置信息
     * @param manageApiParam
     */
    public void update(SystemPositionParam manageApiParam){
        systemPositionBusiness.updateByPrimaryKeySelective(TransformUtils.transform(manageApiParam, SystemPosition.class));
    }
//
//    /**
//     * 删除节点及该节点的子节点
//     * @param id
//     */
//    public void delete(Long id) {
//        systemPositionBusiness.deleteById(id);
//    }

    /**
     * 根据父节点id查找所有该节点下一级的子节点信息
     * @param pid
     * @return
     */
    public List<SystemPosition> queryChildrenByPid(Long pid){
        List<SystemPosition> systemPositionList = systemPositionBusiness.findAllBy("parentId", pid);
        return systemPositionList;
    }

    /**
     * 查询所有的位置
     * @return
     */
    public List<SystemPosition> queryAllPosition(){
        return systemPositionBusiness.findAll();
    }
    /**
     * 查询所有位置信息 pid=0为根节点
     *  positionIds 用户拥有的位置(这里就是所以 以后需要可以查询该用户的位置数) 递归拼成树
     * @return
     */
//    public List<SystemPositionTreeResult> queryAllPositionTree(){
//        List<SystemPosition> allPositionList = queryAllPosition();
//        ArrayList<Long> positionIds = new ArrayList<>();
//        for(SystemPosition p:allPositionList){
//            positionIds.add(p.getId());
//        }
//        //查询根位置列表
//        List<SystemPosition> positionList = queryListByPid(0L, positionIds);
//        queryPositionTreeList(positionList,positionIds);
//        return TransformUtils.transformList(positionList,SystemPositionTreeResult.class);
//    }

    public List<SystemPositionTreeResult> queryAllPositionTree(){
        // 查询出所有的实体集合
        List<SystemPosition> allPositionList = systemPositionBusiness.findAll();
        // 转换成结果集合
        List<SystemPositionTreeResult> systemPositionTreeResults = TransformUtils.transformList(allPositionList, SystemPositionTreeResult.class);
        // toTree
        return toTree(systemPositionTreeResults);
    }

    public List<SystemPositionTreeResult> toTree(List<SystemPositionTreeResult> systemPositionTreeResults) {
        if(CollectionUtils.isEmpty(systemPositionTreeResults))return systemPositionTreeResults;
        return systemPositionTreeResults
                .stream()
                .filter(positionTreeResult -> positionTreeResult.getParentId() == 0)
                .map(positionTreeResult -> {
                    positionTreeResult.setChildren(getChildren(positionTreeResult, systemPositionTreeResults));
                    return positionTreeResult;
                })
                .sorted(Comparator.comparing(SystemPositionTreeResult::getSort))
                .collect(Collectors.toList());
    }

    public List<SystemPositionTreeResult> getChildren(SystemPositionTreeResult root, List<SystemPositionTreeResult> systemPositionTreeResults) {
        if(CollectionUtils.isEmpty(systemPositionTreeResults))return systemPositionTreeResults;
        List<SystemPositionTreeResult> collect = systemPositionTreeResults
                .stream()
                .filter(category -> category.getParentId().equals(root.getId()))
                .map(category->{
                    List<SystemPositionTreeResult> children = getChildren(category, systemPositionTreeResults);
                    category.setChildren(children);
                    //category.setId(null);
                    return category;
                })
                .sorted(Comparator.comparing(SystemPositionTreeResult::getSort))
                .collect(Collectors.toList());
        // 表示没子节点了
        if(CollectionUtils.isEmpty(collect)){
            //root.setName(root.getName());
            // 结束递归
            return new ArrayList<>();
        }
        return collect;
    }

    /**
     * 获取用户的位置节点树 递归
     * @param positionsList 所有节点
     * @param positionIds   用户拥有的节点
     * @return
     */
    public List<SystemPosition> queryPositionTreeList(List<SystemPosition> positionsList,List<Long> positionIds){
        ArrayList<SystemPosition> subPositionList = new ArrayList<>();
        for(SystemPosition entity:positionsList){
            //如果是父节点
            //通过查询该位置id 是否有pid等于该id的来判断是不是叶子节点
            List<SystemPosition> positions = queryChildrenByPid(entity.getId());
            if(ObjectUtils.isNotEmpty(positions)){
                  //todo 有暴漏实体信息的风险
//                entity.setChildren(queryPositionTreeList(queryListByPid(entity.getId(),positionIds),positionIds));
            }
            subPositionList.add(entity);
        }
        return subPositionList;
    }

    /**
     * 查询位置树
     * @param pid
     * @param positionIds 用户拥有的位置节点
     * @return
     */
    public List<SystemPosition> queryListByPid(Long pid,List<Long> positionIds){
        List<SystemPosition> systemPositions = queryChildrenByPid(pid);
        if(ObjectUtils.isEmpty(positionIds)){
            return systemPositions;
        }
        ArrayList<SystemPosition> userPositions = new ArrayList<>();
        for(SystemPosition p:systemPositions){
            if(positionIds.contains(p.getId())){
                userPositions.add(p);
            }
        }
        return userPositions;
    }

    /**
     * 根据位置id 递归删除
     * @param ids
     */
    public void deleteByIds(List<Long> ids){
        if(ObjectUtils.isEmpty(ids)){return;}
        List<SystemPosition> allResourceList=systemPositionBusiness.findAll();
        List<SystemPositionTreeResult> resourceResultList = TransformUtils.transformList(allResourceList, SystemPositionTreeResult.class);
        Set<Long> allIds = new HashSet<>();
        ids.forEach(id->{
            SystemPositionTreeResult root = SystemPositionTreeResult.builder().id(id).build();
            getChildrenIds(root,resourceResultList,allIds);
        });
        allIds.addAll(ids);
        String deleteIds = StringUtils.join(allIds, ",");
        systemPositionBusiness.deleteByIds(deleteIds);
    }

    /**
     * 获取子节点id
     * @param root
     * @param positionList
     * @param childrenIds
     * @return
     */
    public Set<Long> getChildrenIds(SystemPositionTreeResult root, List<SystemPositionTreeResult> positionList, Set<Long> childrenIds) {
        if(ObjectUtils.isEmpty(positionList))return childrenIds;
        positionList
                .stream()
                .filter(position -> position.getParentId().equals(root.getId()))
                .map(position->{
                    childrenIds.add(position.getId());
                    getChildrenIds(position, positionList,childrenIds);
                    return position;
                })
                .collect(Collectors.toList());
        return childrenIds;
    }

}
